package com.atguigu.hadoop.examples.mapreduce.wordMedian;


import com.google.common.base.Charsets;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class WordMedian extends Configured
        implements Tool {
    private double median = 0.0D;
    public static final IntWritable ONE = new IntWritable(1);

    private double readAndFindMedian(String path, int medianIndex1, int medianIndex2, Configuration conf)
            throws IOException {
        FileSystem fs = FileSystem.get(conf);
        Path file = new Path(path, "part-r-00000");

        if (!fs.exists(file)) {
            throw new IOException("Output not found!");
        }
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(fs.open(file), Charsets.UTF_8));
            int num = 0;
            String line;
            while ((line = br.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(line);

                String currLen = st.nextToken();

                String lengthFreq = st.nextToken();

                int prevNum = num;
                num += Integer.parseInt(lengthFreq);

                if ((medianIndex2 >= prevNum) && (medianIndex1 <= num)) {
                    System.out.println("The median is: " + currLen);
                    br.close();
                    return Double.parseDouble(currLen);
                }
                if ((medianIndex2 >= prevNum) && (medianIndex1 < num)) {
                    String nextCurrLen = st.nextToken();

                    double theMedian = (Integer.parseInt(currLen) +
                            Integer.parseInt(nextCurrLen)) /
                            2.0D;
                    System.out.println("The median is: " + theMedian);
                    br.close();
                    return theMedian;
                }
            }
        } finally {
            if (br != null) {
                br.close();
            }
        }

        return -1.0D;
    }

    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Configuration(), new WordMedian(), args);
    }

    public int run(String[] args) throws Exception {
        Configuration conf = new Configuration();

        String[] otherArgs = new GenericOptionsParser(conf, args)
                .getRemainingArgs();
        if (otherArgs.length != 2) {
            System.err.println("Usage: wordmedian <in> <out>");
            return 0;
        }

        setConf(conf);

        Job job = Job.getInstance(conf, "word median");
        job.setJarByClass(WordMedian.class);
        job.setMapperClass(WordMedianMapper.class);
        job.setCombinerClass(WordMedianReducer.class);
        job.setReducerClass(WordMedianReducer.class);
        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(IntWritable.class);
        FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
        FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
        boolean result = job.waitForCompletion(true);

        long totalWords = ((CounterGroup) job.getCounters()
                .getGroup(TaskCounter.class
                        .getCanonicalName()))
                .findCounter("MAP_OUTPUT_RECORDS", "Map output records")
                .getValue();
        int medianIndex1 = (int) Math.ceil(totalWords / 2.0D);
        int medianIndex2 = (int) Math.floor(totalWords / 2.0D);

        this.median = readAndFindMedian(args[1], medianIndex1, medianIndex2, conf);

        return result ? 0 : 1;
    }

    public double getMedian() {
        return this.median;
    }


}